package com.supreme.cacheserver.config.condition;

import org.apache.commons.lang3.reflect.MethodUtils;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.ClassUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.Objects;

public class CacheConfigCondition implements Condition {

    public static final String[] RedisCacheConfig = new String[]{"RedisCacheConfig", "redis"};
    public static final String[] CaffeineCacheConfig = new String[]{"CaffeineCacheConfig", "caffeine"};

    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        Environment environment = conditionContext.getEnvironment();
        String cacheTypeProperty = environment.getProperty("cache-server.cacheType");
        if (Objects.isNull(cacheTypeProperty)) {
            return false;
        }

        try {
            String className = (String) MethodUtils.invokeMethod(annotatedTypeMetadata, "getClassName");
            String classShortName = ClassUtils.getShortName(className);
            if (RedisCacheConfig[0].equals(classShortName)) {
                return RedisCacheConfig[1].equalsIgnoreCase(cacheTypeProperty);
            }
            if (CaffeineCacheConfig[0].equals(classShortName)) {
                return CaffeineCacheConfig[1].equalsIgnoreCase(cacheTypeProperty);
            }
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }

        return false;
    }
}
